package com.jhoncy.myproject.system.ctrl;

import com.jhoncy.myproject.common.dto.PageResponse;
import com.jhoncy.myproject.common.dto.RestResponse;
import com.jhoncy.myproject.common.security.oauth.dto.CustomUserDetails;
import com.jhoncy.myproject.system.entity.SysUser;
import com.jhoncy.myproject.system.service.SysUserService;
import com.jhoncy.myproject.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * 用户
 * @author zhuangqi
 * @@date 2017/3/14.
 */
@RestController
@RequestMapping(value = "/sys/user")
public class SysUserCtrl {

    @Autowired
    private SysUserService sysUserService;


    /**
     * 获取所有用户
     * @return
     */
    @GetMapping
    public PageResponse<List<SysUser>> listUser(@RequestParam(required = false) String start,
                                                    @RequestParam(required = false) String rows) {
        int page_start = PageUtil.parseStart(start);
        int page_rows = PageUtil.parseRows(rows);
        PageResponse<List<SysUser>> response = new PageResponse<>(page_start,page_rows);
        List<SysUser> users = sysUserService.listUser(page_start,page_rows);
        response.setCount(users.size());
        response.setData(users);
        return response;
    }

    /**
     * access_token获取用户信息
     * @param principal
     * @return
     */
    @GetMapping(value = "/userDetails")
    public RestResponse<CustomUserDetails> getUser(Principal principal) {
        RestResponse<CustomUserDetails> response = new RestResponse<>();
        CustomUserDetails user = (CustomUserDetails) sysUserService.loadUserByUsername(principal.getName());
        response.setData(user);
        return response;
    }

    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @PostMapping
    public RestResponse saveUser(@RequestBody SysUser sysUser){
        RestResponse response = new RestResponse();
        sysUserService.saveUser(sysUser);
        response.setMessage("新增用户成功 !");
        return response;
    }

    /**
     * 更新用户
     * @param userId
     * @param sysUser
     * @return
     */
    @PutMapping("/{userId}")
    public RestResponse updateUser(@PathVariable String userId,@RequestBody SysUser sysUser) {
        RestResponse response = new RestResponse();
        sysUserService.updateUser(userId,sysUser);
        response.setMessage("更新用户成功 !");
        return response;
    }

    @DeleteMapping("/{userId}")
    public RestResponse deleUser(@PathVariable String userId) {
        RestResponse response = new RestResponse();
        sysUserService.deleUser(userId);
        return response;
    }
}
